﻿using UnityEngine;
using System.Collections;

public class Shooting : MonoBehaviour {

	public GameObject bullet;
	public float rate = 1f;
	public float t = 0f;
	
	// Update is called once per frame
	void Update () {


		t += Time.deltaTime; // aika kuluu


		// hiiren nappi 0:sta ampuu
		if (Input.GetMouseButton(0) && t>1f/rate && GameManager.player_destroyed == false && transform.parent.localEulerAngles.x > 270f) {

			t = 0f;// nollataan aikalaskuri

			GameObject clone;

			// luodaan bulletista klooni
			clone = Instantiate(bullet,
			                    transform.position,
			                    Quaternion.identity) as GameObject;

			// laitetaan vauhtia luodille
			clone.rigidbody2D.velocity = (new Vector3(0,0,PlayerControls.move_speed * 1.5f) + transform.forward * 20f);

			//
			LookAtZ(clone, clone.transform.position + (Vector3)clone.rigidbody2D.velocity);



			// klooni tuhotaan x sekunnin päästä
			Destroy (clone, 1.5f);
		
		}

	
	}

	void LookAtZ(GameObject ob, Vector3 target_pos)
	{
		Vector3 dir = target_pos-ob.transform.position;
		dir.Normalize();
		
		Quaternion target_q = ob.transform.rotation;
		
		if(dir.x > 0f && dir.x > Mathf.Abs(dir.y))// oikeelle
			target_q = Quaternion.LookRotation(target_pos - ob.transform.position,Vector3.down);
		if(dir.x < 0f && dir.x < -Mathf.Abs(dir.y))// vasemmalle
			target_q = Quaternion.LookRotation(target_pos - ob.transform.position,Vector3.up);
		
		if(dir.y > 0f && dir.y > Mathf.Abs(dir.x))// ylös
			target_q = Quaternion.LookRotation(target_pos - ob.transform.position,Vector3.right);
		if(dir.y < 0f && dir.y < -Mathf.Abs(dir.x))// alas
			target_q = Quaternion.LookRotation(target_pos - ob.transform.position,Vector3.left);
		
		target_q.x=0;
		target_q.y=0;
		
		ob.transform.rotation = target_q;
	}
}
